package tgc.edu.ljc.bookmanage.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import tgc.edu.ljc.bookmanage.custom.CommonService;
import tgc.edu.ljc.bookmanage.entity.TbDept;
import tgc.edu.ljc.bookmanage.repository.TbDeptRepository;

@Service
public class TbDeptService extends CommonService<TbDept, Integer>{
	@Autowired
	private TbDeptRepository tbDeptDAO;
	
	public List<TbDept> findByParentIsNull() {
		List<TbDept> list = tbDeptDAO.findByParentIsNull();
		return list;
	}

	public List<TbDept> findByParentId(Integer id) {
		List<TbDept> root = tbDeptDAO.findByParentId(id);
		return root;
	}

	public List<HashMap<String, Object>> findTreeByParentIsNull(){
		List<HashMap<String, Object>> result=new ArrayList<>();
		List<TbDept> root = findByParentIsNull();
		for (TbDept dept : root) {
			HashMap<String, Object> node=new HashMap<>();
			node.put("id", dept.getId());
			node.put("name",dept.getName());
			node.put("manager",dept.getManager());
			node.put("children",findTreeByParentId(dept.getId()));
			result.add(node);
		}
		return result;
	}
	
	public List<HashMap<String, Object>> findTreeByParentId(Integer id){
		List<HashMap<String, Object>> result=new ArrayList<>();
		List<TbDept> root = findByParentId(id);
		for (TbDept dept : root) {
			HashMap<String, Object> node=new HashMap<>();
			node.put("id", dept.getId());
			node.put("name",dept.getName());
			node.put("manager",dept.getManager());
			node.put("children",findTreeByParentId(dept.getId()));
			result.add(node);
		}
		return result;
	}

	
	/***
	 * 生成combotree的节点数据
	 * @param id 父节点的id
	 * @param nodeId 树中要排除的节点的id
	 * @return combotree的节点数据
	 */
	public List<HashMap<String, Object>> combotree(Integer id, Integer nodeId) {
		List<HashMap<String, Object>> result=new ArrayList<>(); 
		List<TbDept> root;
		if(id!=null) {
			root=findByParentId(id);
		}else {
			root = findByParentIsNull();
		}
		for (TbDept dept : root) {
			if(dept.getId()==nodeId) {
				continue;
			}
			HashMap<String, Object> node=new HashMap<>();
			node.put("id", dept.getId());
			node.put("text",dept.getName());
			if(dept.getChildren().size()>0) {
				node.put("state","closed");
				node.put("children", combotree(dept.getId(),nodeId));
			}
			result.add(node);
		}
		return result;
	}

}
